<?php
namespace Home\Controller;

class CommonController extends \Think\Controller{
	
    protected $appid;
    protected $access_token;
    protected $fromuser;
    public function _initialize(){
        header("Content-Type: text/html; charset=utf-8");
        //获取openid
    /*     if(session(C('OPENID'))){
            $this->fromuser = session(C('OPENID'));
        }else{
            $appconfig = D('Customer')->find(1);
            $appid = $appconfig['appid'];
            $secret = $appconfig['appsecret'];
            if($_REQUEST['code']){
                $code=$_REQUEST['code'];
                $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
                $json_result = D('Api')->curl_request($url);
                $result = json_decode($json_result,true);
                if(!$result['openid']){
                    $this->error("获取用户信息失败，原因：未关注此公众号，或未知错误");
                }
                $this->fromuser = $result['openid'];
                session(C('OPENID'),$this->fromuser);
                
            }else{
                $redirectUri = urlencode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);//openid处理页面(当前页面)
                header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirectUri&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect");
                die;
            }
        } */
        $this->fromuser = 'b';
        $this->assign('fromuser',$this->fromuser);
    }
    protected function ini_wx() {
    	$app_args = D('Customer')->find(C('CUSTOMER_ID'));
    	$appid = $app_args['appid'];
    	$secret = $app_args['appsecret'];
    	$this->appid = $app_args['appid'];
    	$this->access_token = D('Customer')->getToken($appid,$secret);
    }
    protected function getSignPackage() {
    	$jsapiTicket = $this->getJsApiTicket();
        
    	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    	$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    	$timestamp = time();
    	$nonceStr = $this->createNonceStr();
    
    	// 这里参数的顺序要按照 key 值 ASCII 码升序排序
    	$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    
    	$signature = sha1($string);
    
    	$signPackage = array(
    			"appId"     => $this->appid,
    			"nonceStr"  => $nonceStr,
    			"timestamp" => $timestamp,
    			"url"       => $url,
    			"signature" => $signature,
    			"rawString" => $string
    	);
    	return $signPackage;
    }
    
    protected function createNonceStr($length = 16) {
    	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    	$str = "";
    	for ($i = 0; $i < $length; $i++) {
    		$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    	}
    	return $str;
    }
    
    protected function getJsApiTicket() {
    	$this->ini_wx();
    	// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
    	$jsapi_ticket_data = D('Jsapi')->find();

    	if (!$jsapi_ticket_data || $jsapi_ticket_data['expire_time'] < time()) {
            
    		$accessToken = $this->access_token;
            
    		// 如果是企业号用以下 URL 获取 ticket
    		// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
    		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
    		$res = json_decode(curl_request($url));
            $ticket = $res->ticket;
    		if ($ticket) {
    			$data = array();
    			$data['ticket'] = $ticket;
    			$data['expire_time'] = time() + 7000;
                if(!empty($jsapi_ticket_data['id'])){
                    D('Jsapi')->where("id='{$jsapi_ticket_data['id']}'")->save($data);
                }else{
                    D('Jsapi')->add($data);
                }
    		}
    	} else {
    		$ticket = $jsapi_ticket_data['ticket'];
    	}
    	return $ticket;
    }
    
    public function checkUser() {
        
        return true;
    }
    
    //验证码
    public function code() {
        vendor("Captcha.captcha");
        $w = I('width') ? (int)I('width') : 80;
        $h = I('height') ? (int)I('height') : 35;
        $code = new \Captcha($_SERVER['DOCUMENT_ROOT'] . '/wechat/Public/captcha/', $w, $h);
        @ob_end_clean(); //清除之前出现的多余输入
        $code->generate_image();
    }
    
    //发送模板消息
    public function sendTmpMsg($datas=array(),$type=1){
        ini_wx();
        vendor('TmpMsg.TmpMsg');
        if(empty($datas)||empty($user))return false;
        $tmpmsg = new \TmpMsg($this->access_token);
        return $tmpmsg->sendMsg($this->fromuser,$datas,$type);
    }
    
    //发送站内消息
    public function sendWebMsg($msg,$user_id){
        if(empty($msg)||empty($user_id)){
            return false;
        }
        if(D('Users')->where("user_id='$user_id'")->find()){
            return false;
        }
        if(D('WxWebMsg')->add(array('user_id'=>$user_id,'content'=>$msg))){
            return true;
        }else{
            return false;
        }
    }
    
}